package com.talkweb.osmharmony.views.overlay.compass;

import ohos.app.Context;
import ohos.sensor.agent.CategoryOrientationAgent;
import ohos.sensor.bean.CategoryOrientation;
import ohos.sensor.data.CategoryOrientationData;
import ohos.sensor.listener.ICategoryOrientationDataCallback;

public class InternalCompassOrientationProvider implements ICategoryOrientationDataCallback, IOrientationProvider {
    private IOrientationConsumer mOrientationConsumer;
    private CategoryOrientationAgent mSensorManager;
    private float mAzimuth;

    public InternalCompassOrientationProvider(Context context) {
        mSensorManager = new CategoryOrientationAgent();
    }

    //
    // IOrientationProvider
    //

    /**
     * Enable orientation updates from the internal compass sensor and show the compass.
     */
    @Override
    public boolean startOrientationProvider(IOrientationConsumer orientationConsumer) {
        mOrientationConsumer = orientationConsumer;
        boolean result = false;
        CategoryOrientation sensor = mSensorManager.getSingleSensor(CategoryOrientation.SENSOR_TYPE_ORIENTATION);
        if (sensor != null) {
            result = mSensorManager.setSensorDataCallback(this, sensor, sensor.getMinInterval());
        }
        return result;
    }

    @Override
    public void stopOrientationProvider() {
        mOrientationConsumer = null;
        mSensorManager.releaseSensorDataCallback(this);
    }

    @Override
    public float getLastKnownOrientation() {
        return mAzimuth;
    }

    @Override
    public void destroy() {
        stopOrientationProvider();
        mOrientationConsumer = null;
        mSensorManager = null;
    }


    @Override
    public void onSensorDataModified(CategoryOrientationData categoryOrientationData) {
        if (categoryOrientationData.values != null) {
            mAzimuth = categoryOrientationData.values[0];
            if (mOrientationConsumer != null)
                mOrientationConsumer.onOrientationChanged(mAzimuth, this);
        }
    }

    @Override
    public void onAccuracyDataModified(CategoryOrientation categoryOrientation, int i) {

    }

    @Override
    public void onCommandCompleted(CategoryOrientation categoryOrientation) {

    }
}
